App({

  /**
   * 全局变量
   */
  globalData: {
    user_id: null,
    hasLogin: false,     //全局登录
  },

  api_root: '', // api地址
  siteInfo: require('siteinfo.js'),

  /**
   * 初始化，全局触发一次
   */
  onLaunch: function() {   //启动后触发
    // 设置api地址
    this.setApiRoot();
    // 获取小程序基础信息
    this.getWxappBase(function (wxapp) {
      // 设置navbar标题、颜色
      wx.setNavigationBarColor({
        frontColor: wxapp.navbar.top_text_color.text,
        backgroundColor: wxapp.navbar.top_background_color
      })
    });
    this.getUserDetail();    //获取当前用户信息,看是否注册
  },

  

  /**
   * 设置api地址
   */
  setApiRoot: function() {
    this.api_root = this.siteInfo.siteroot ;
    this.uploadimgRoot = this.siteInfo.uploadimgRoot;   //上传图片地址
  },

  /**
   * 获取小程序基础信息
   */
  getWxappBase: function(callback) {
    let App = this;
    App._get('api/base', {}, function(result) {
      // 记录小程序基础信息
      wx.setStorageSync('wxapp', result.data.wxapp);
      callback && callback(result.data.wxapp);
    }, false, false);
  },

  
  /**
  * 获取当前用户信息
  */
  getUserDetail: function () {
    let _this = this;
    _this._get('api/user_detail', {}, function (result) {
      //console.log(result);
      if (result.code == -1) return _this.jmlogin();  //静默获取，这里用于服务器缓存被删了的情况
      if(result.code==1){
        //成功则更新缓存
        _this.globalData.hasLogin = true ;
        _this.globalData.user_id = result.data.userInfo.id;
        wx.setStorageSync('user_id',result.data.userInfo.id);
      }
    });
  },

  /*静默获取用户信息*/

  jmlogin:function(){
    let App = this;
    wx.login({
      success: function (res) {
        // 发送用户信息
        App._post_form('api/gettoken'
          , {
            code: res.code,
          }
          , function (result) {
            if(result.code==1){
              _this._get('api/user_detail', {}, function (result) {
                if (result.code == 1) {
                  //成功则更新缓存
                  _this.globalData.hasLogin = true;
                  _this.globalData.user_id = result.data.userInfo.id;
                  wx.setStorageSync('user_id', result.data.userInfo.id);
                }
              });
            } 
          }
          , false
          , function () {
            wx.hideLoading();
          });
      }
    });
  },









  /**
   * 当前用户id
   */
  getUserId: function() {
    return wx.getStorageSync('user_id');
  },

  /**
   * 显示成功提示框
   */
  showSuccess: function(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      success: function() {
        callback && (setTimeout(function() {
          callback();
        }, 1500));
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showError: function(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        callback && callback();
      }
    });
  },

  /**
   * get请求
   */
  _get: function(url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();  //加载动画条
    let App = this;
    // 构造请求参数
    data = data || {};
    data.wxapp_id = App.siteInfo.uniacid;

    // if (typeof check_login === 'undefined')
    //   check_login = true;

    // 构造get请求
    let request = function() {
      data.token = wx.getStorageSync('token');       //获取本地缓存
      wx.request({
        url: App.api_root + url,
        header: {
          'content-type': 'application/json'
        },
        data: data,
        success: function(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            console.log(res);
            App.showError('网络请求出错');
            return false;
          }
         if (res.data.code === 0) {
            App.showError(res.data.msg);
            return false;
          } else {
            success && success(res.data);
          }
        },
        fail: function(res) {
          wx.hideToast();
          App.showError('网络出错', function() {
            fail && fail(res);
          });
        },
        complete: function(res) {
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? App.doLogin(request) : request();
  },


  /**
   * post提交
   */
  _post_form: function(url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    let App = this;
    data.wxapp_id = App.siteInfo.uniacid;
    data.token = wx.getStorageSync('token');
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showError('网络请求出错');
          return false;
        }
        if (res.data.code === 0) {
          App.showError(res.data.msg, function() {
            fail && fail(res);
          });
          return false;
        }
        success && success(res.data);
      },
      fail: function(res) {
        // console.log(res);
        App.showError('网络请求出错', function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        complete && complete(res);
      }
    });
  },

  

  /**
   * 对象转URL
   */
  urlEncode: function urlencode(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(function(_value) {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },

  /**
   * 设置当前页面标题
   */
  setTitle: function() {
    let App = this,wxapp;
    if (wxapp = wx.getStorageSync('wxapp')) {
      wx.setNavigationBarTitle({
        title: wxapp.navbar.wxapp_title
      });
    } else {
      App.getWxappBase(function() {
        App.setTitle();
      });
    }
  },

});